package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.feigns.admin.AdminFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    //内容审核用
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    GreenTextScan textScan;
    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //边界条件,无需登录,登录时判断点赞哪些评论即可
        if (dto==null ||dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize()==null || dto.getSize()<=0){
            dto.setSize(20);
        }
        List<ApCommentRepay> commentRepays = mongoTemplate.find(
                Query.query(
                        Criteria.where("commentId").is(dto.getCommentId())
                                .and("createdTime").lt(dto.getMinDate())
                ).limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC, "createdTime"))
                , ApCommentRepay.class
        );
        ApUser user = AppThreadLocalUtils.getUser();
        //未登录时返回数据即可
        if (user==null || user.getId()==null){
            return ResponseResult.okResult(commentRepays);
        }
        //登录时需要封装点赞信息*****查找到点赞信息并遍历封装返回
        List<ApCommentRepayVo> resultList = new ArrayList<>();
        List<String> idList = commentRepays.stream().map(u -> u.getId()).collect(Collectors.toList());
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(
                Query.query(
                        Criteria.where("commentRepayId").in(idList)
                                .and("authorId").is(user.getId())
                )
                , ApCommentRepayLike.class
        );
        //存在喜欢时回显
        if (commentRepays!=null &&commentRepays.size()>0 &&apCommentRepayLikes!=null && apCommentRepayLikes.size()>0){
            commentRepays.stream().forEach(commentRepay->{
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(commentRepay,apCommentRepayVo);
                apCommentRepayLikes.stream().forEach(u->{
                    if (commentRepay.getId().equals(u.getCommentRepayId())){
                        apCommentRepayVo.setOperation((short) 0);
                    }
                });
                resultList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(resultList);
        }
        //不存在时直接返回
        return ResponseResult.okResult(commentRepays);
    }

    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //边界条件  对评论内容长度限制  ，此功能需要登录并且需求审核内容
        if (dto==null ||dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"回复不能为空");
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null || user.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = userFeign.findUserById(user.getId());
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"登录信息错误");
        }
        //文字内容审核---阿里组件，自定义敏感词
        boolean isSensitiveScan = handleSensitive(dto.getContent());
        if (!isSensitiveScan){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论不符合社会主义核心价值观");
        }
        /*boolean isTextScan = handleTextScan(dto.getContent());
        if (!isTextScan){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论不符合社会主义核心价值观");
        }*/
        //保存回复响应结果,  ********保存回复后需更新评论的回复数
        ApCommentRepay commentRepay = ApCommentRepay.builder()
                .authorId(apUser.getId())
                .authorName(apUser.getName())
                .content(dto.getContent())
                .commentId(dto.getCommentId())
                .createdTime(new Date())
                .updatedTime(new Date())
                .likes(0)
                .build();
        mongoTemplate.insert(commentRepay);//保存回复信息
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);//更新评论回复数

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞与取消  回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //边界条件  需要登录
        if (dto==null || dto.getCommentRepayId()==null ||dto.getOperation()<0 ||dto.getOperation()>1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null||user.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //先查找再更新
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        /**
         * 0点赞  1取消   不可重复操作,先查找点赞信息再过呢更新
         */
        ApCommentRepayLike apCommentLike = mongoTemplate.findOne(
                Query.query(Criteria.where("authorId").is(user.getId())
                        .and("commentRepayId").is(dto.getCommentRepayId())),
                ApCommentRepayLike.class
        );
        Map<String, Object> resultMap = new HashMap<>();//结果map,响应当前评论点赞数给前端
        if (dto.getOperation()==0){
            if (apCommentLike!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"不可重复点赞");
            }
            //设置点赞数+1并存入回复点赞表
            commentRepay.setLikes(commentRepay.getLikes()+1);
            mongoTemplate.save(commentRepay);//回复点赞数+1
            ApCommentRepayLike repayLike = ApCommentRepayLike.builder()
                    .authorId(user.getId())
                    .commentRepayId(dto.getCommentRepayId())
                    .operation(dto.getOperation())
                    .build();
            mongoTemplate.save(repayLike);//保存回复点赞信息
            resultMap.put("likes",commentRepay.getLikes());
            return ResponseResult.okResult(resultMap);
        }

        if (apCommentLike==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"不可重复操作");
        }
        commentRepay.setLikes(commentRepay.getLikes()<=0?0:(commentRepay.getLikes()-1));//回复点赞数-1
        mongoTemplate.remove(
                Query.query(
                        Criteria.where("authorId").is(user.getId())
                        .and("commentRepayId").is(dto.getCommentRepayId())
                )
                ,ApCommentRepayLike.class
        );//回复点赞信息移除

        resultMap.put("likes",commentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 自管理敏感词审核
     * @param content
     * @return
     */
    private boolean handleSensitive(String content) {
        boolean flag = true;
        List<String> sensitives = adminFeign.findAllSensitive();

        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size()>0){
            flag=false;
        }
        return flag;
    }

    /**
     * 阿里云文字审核
     * @param content
     * @return
     */
    private boolean handleTextScan(String content){
        boolean flag=true;
        try {
            Map map = textScan.greeTextScan(content);
            if (map.get("suggestion").equals("block")||map.get("suggestion").equals("review")){
                flag=false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
